import java.util.*;

/**
 * @author LKQ
 * @date 2022/4/9 18:04
 * @description 双指针，统计左右括号的个数
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.longestValidParentheses("(()(((()"));
    }

    public int longestValidParentheses(String s) {
        int left = 0, right = 0;
        int max = 0;
        int n = s.length();
        char[] S = s.toCharArray();
        // 正序遍历一次
        for (int i = 0; i < n; i++) {
            if (S[i] == '(') {
                left++;
            } else {
                right++;
            }
            if (right == left) {
                max = Math.max(max, 2 * left);
            } else if (right > left) {
                left = 0;
                right = 0;
            }
        }
        left = right = 0;
        for (int i = n - 1; i >= 0; i--) {
            if (S[i] == '(') {
                left++;
            } else {
                right++;
            }
            if (right == left) {
                max = Math.max(max, 2 * right);
            } else if (left > right) {
                left = 0;
                right = 0;
            }
        }
        return max;
    }
}
